package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferRelInfo;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import com.ztesoft.bss.common.exception.BssException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description 五大双线，起租页面
 * 对于本次受理新增资费：如果资费生效模式为“起租时间生效”则需要刷新资费项的生效时间=起租时间；
 * 对于存量有效资费：如果本次失效模式受理做了修改，资费项失效模式变为“起租时间-1失效”，则需要刷新资费项的失效时间=起租时间-1S（如果存量资费本次操作失效模式未做修改，则不需要刷新资费失效时间）
 * 其余情况不对做根据起租时间对资费生效时间和失效时间进行刷新。
 *
 * 国际产品：起租时间不能早于当月第一天
 * @Author deng.gang
 * @Date 2021/10/28 10:34 上午
 */
@Service
public class DoubleLineRentStartTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Override
    public void init(CommonAttrVO commonAttr) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if (KiteStringUtils.isNotEmpty(value)) {

            // 国际SDH、国际以太网、国际互联网，起租时间不能早于当月第一天
            KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
            String province = sceneInst.getProvinceNbr();
            String offerId = Optional.ofNullable(querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId())).map(KiteOfferInst::getOfferId).orElse(null);
            if(KiteStringUtils.isEqual(offerId, "50040853") && KiteStringUtils.equalsAny(province, "48","49")
                || KiteStringUtils.equalsAny(offerId, "50040445","50040470","50040534","50040654","50040655","50040657")) {
                LocalDate targetDate = null;
                try {
                    targetDate = LocalDate.parse(value, DateTimeFormatter.ofPattern(DateFormatUtils.DATE_FORMAT));
                } catch (Exception e) {
                    ErrorConsts.SYSTEM_ERROR.throwOut(e.getMessage());
                }
                // 当月第一天
                LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
                if (targetDate.isBefore(firstDayOfMonth)) {
                    BssException.throwOut("", "", "起租时间不能早于当月第一天");
                }
            }

            // 生效模式=起租时间生效，刷新资费项的生效时间=起租时间
            this.refreshStartTime(sceneInstId, value);
        }

        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    /**
     * 生效模式=起租时间生效，刷新资费项的生效时间=起租时间
     */
    private void refreshStartTime(String sceneInstId, String value) {
        // 获取所有的主套餐包括促销
        List<KiteOfferInst> offerInsts = Lists.newArrayList();
        offerInsts.addAll(querySceneInstService.listMainOfferInsts(sceneInstId));
        offerInsts.addAll(querySceneInstService.listPromotionOfferInsts(sceneInstId));
        for (KiteOfferInst offerInst : offerInsts) {
            if (KiteStringUtils.isEqual(offerInst.getActionType().name(), ActionType.D.name())) {
                continue;
            }
            //查询所有的可选包规格
            List<OfferRelInfo> offerRelInfoList = OfferCache.get(offerInst.getOfferId()).listAllOfferRels().stream().filter(offerRelInfo -> {
                return CoreDataOffer.OFF_0005_12.equals(offerRelInfo.getzOfferType());
            }).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(offerRelInfoList)) {
                continue;
            }
            List<KiteOfferInst> additionalOfferInsts = querySceneInstService.listAdditionalOfferInstsFromOfferInst(KiteWebContext.getContext().getCustId(), offerInst.getOfferInstId());
            if (KiteListUtils.isNotEmpty(additionalOfferInsts)) {
                additionalOfferInsts.forEach(additionalOfferInst -> {
                    KiteAttr effModeAttr = additionalOfferInst.getAttr("200000174"); // 生效模式
                    KiteAttr expModeAttr = additionalOfferInst.getAttr("200001735"); // 失效模式
                    StringBuffer newStartRentTimeBf = new StringBuffer(value);
                    if (newStartRentTimeBf.length() == 10) {
                        newStartRentTimeBf.append(" 00:00:00");
                    }
                    // 对于本次受理新增资费：如果资费生效模式为“起租时间生效”则需要刷新资费项的生效时间=起租时间
                    if (ActionType.A.equals(additionalOfferInst.getActionType()) && Objects.nonNull(effModeAttr) &&
                        KiteStringUtils.equals(effModeAttr.getValue(), LocalKeyConsts.EFFECTIVE_STARTING_TIME)) {
                        operateInstAttrService.setAttrValue(additionalOfferInst, LocalKeyConsts.STARTING_DATE_FIELD_NAME, newStartRentTimeBf.toString(), sceneInstId, null);
                    }
                    // 对于修改的资费：如果再次修改了起租时间，则需要刷新失效时间（资费项失效模式变为起租时间-1失效）
                    if (ActionType.M.equals(additionalOfferInst.getActionType()) && Objects.nonNull(expModeAttr) &&
                        KiteStringUtils.isNotEmpty(expModeAttr.getPreValue()) && !KiteStringUtils.equals(expModeAttr.getOriginValue(), expModeAttr.getValue()) &&
                        KiteStringUtils.equals(expModeAttr.getValue(), LocalKeyConsts.STARTING_TIME_INVALIDATION)) {
                        String expireTime = DateFormatUtils.addDate(newStartRentTimeBf.toString(), DateFormatUtils.DATE_TIME_FORMAT, -1, DateFormatUtils.SECOND);
                        operateInstAttrService.setAttrValue(additionalOfferInst, LocalKeyConsts.END_DATE_FIELD_NAME, expireTime, sceneInstId, null);
                    }
                });
            }
        }
    }
}
